package server.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import server.http.HttpResponseContent;
import server.service.LoginService;

import java.util.HashMap;
import java.util.Objects;


@CrossOrigin
@RestController
@RequestMapping(method = {RequestMethod.POST, RequestMethod.OPTIONS}, value = "login")
@SuppressWarnings("unused")
public class LoginController {

    private static final Logger log = LogManager.getLogger(LoginController.class);
    @Resource
    private LoginService loginService;

    @PostMapping("")
    public JSONObject login(@RequestBody HashMap<String, Object> request, HttpServletRequest req) {
        JSONObject res;
        if (request.isEmpty()) {
            res = HttpResponseContent.FIELD_INFO.get("body_empty", JSONObject.class);
        } else {
            res = loginService.login(request, req);
        }
        return res;
    }

    @PostMapping("verity")
    public JSONObject tokenVerity(HttpServletRequest request) {
        // 需要处理用户是否已经登录的状态，需要验证token 在redis 缓存中的状态
        String getToken = request.getHeader("Token");
        if (Objects.nonNull(getToken) && StrUtil.isNotEmpty(getToken)) {
            return loginService.verityLoginStatus(getToken);
        } else {
            return HttpResponseContent.LOGIN_INFO.get("expire", JSONObject.class);
        }
    }

    @PostMapping("logout")
    public JSONObject logout(HttpServletRequest request){
        return loginService.logout(request);
    }
}
